package com.stockz.ui.swing.charting.util;

import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;

import com.stockz.core.util.Global;
import com.stockz.ui.swing.charting.view.StockChartPanel;

public class SetStockChartViewPortUtil{

	static{
		Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener(){
		    public void eventDispatched(AWTEvent e){
		    	if(e instanceof KeyEvent){
		    		KeyEvent keyEvent = (KeyEvent)e;
			       if(!keyEvent.isConsumed() && keyEvent.getID() == KeyEvent.KEY_RELEASED 
			    		   &&  keyEvent.getKeyCode() == KeyEvent.VK_RIGHT && keyEvent.isControlDown()){
			    	   keyEvent.consume();
			    	   StockChartPanel stockChartPanel = (StockChartPanel)Global.get(UIChartingConstant.SelectedStockChartPanel);
			    	   if(stockChartPanel != null){
			    		   setStockChartViewPort(stockChartPanel);
			    	   }
			       }
		    	}
		    }
		}, AWTEvent.KEY_EVENT_MASK);
	}
	
	
	public static void setStockChartViewPort(StockChartPanel stockChartPanel) {
			Dimension dimension = stockChartPanel.getSize();
			if(dimension == null || (dimension.width == 0 && dimension.height == 0)){
				dimension = stockChartPanel.getPreferredSize();
			}
			
			Rectangle visibleRectangle = stockChartPanel.getVisibleRect();
			
			int x = stockChartPanel.getLocation().x 
			+ dimension.width - visibleRectangle.width;
			
			
			Rectangle rectangle = new Rectangle(
				x,
				stockChartPanel.getLocation().y,
				visibleRectangle.width,
				visibleRectangle.height);
		
			stockChartPanel.getView().getScrollPane().getViewport().scrollRectToVisible(rectangle);
	}

	
	
	public static void setStockChartViewPort(StockChartPanel stockChartPanel,int multiple) {
		Rectangle rectangle = stockChartPanel.getView().getScrollPane().getViewport().getViewRect();
		rectangle.x += multiple*stockChartPanel.getStockChartPanelState().getTimeUnitSpace();
		stockChartPanel.getView().getScrollPane().getViewport().scrollRectToVisible(rectangle);
	}
}
